﻿using AutoMapper;
using MediatR;
using ProductionManagement.Application.Command.StrippingCommand;
using ProductionManagement.Domain.ProductionDomain;
using ProductionManagement.Infrstructre.lnterface;
using SqlSugar;

namespace ProductionManagement.Application.CommandHandler.StrippingCommandHandler
{
    public class AddStrippingProductCommandHandler : IRequestHandler<AddStrippingProductCommand, int>
    {
        IStrippingRepository sRep;
        IStripProductRepostory spRep;
        ISqlSugarClient db;
        IMapper mapper;

        public AddStrippingProductCommandHandler(IStrippingRepository sRep,
        IStripProductRepostory spRep, ISqlSugarClient db, IMapper mapper)
        {
            this.sRep = sRep;
            this.spRep = spRep;
            this.db = db;
            this.mapper = mapper;
        }

        public async Task<int> Handle(AddStrippingProductCommand request, CancellationToken cancellationToken)
        {
            // 开始事务
            db.Ado.BeginTran();

            try
            {
                //添加补料
                var strip = mapper.Map<Stripping>(request.AddDto);
                strip.StripNumber = Guid.NewGuid().ToString();
                var taskToAdd = await sRep.AddAsync(strip);


                //添加补料产品
                foreach (var item in request.AddDto.strippingProducts)
                {
                    StripProduct detail = new StripProduct
                    {
                        ProductId = item.ProductId,
                        StripNumber = strip.StripNumber,
                        Office_Id = item.Office_Id,
                        User_Id = item.User_Id,
                        StripProductNum = item.StripProductNum,
                    };
                    await spRep.AddAsync(detail);
                }

                // 提交事务
                db.Ado.CommitTran();

                return 1;  // 返回最终的结果
            }
            catch (Exception)
            {
                // 回滚事务
                db.Ado.RollbackTran();
                throw;
            }
        }
    }
}
